import { PermissionModel } from '../../schemas/system/Permission';
import { Permission } from '../../types';
import { HttpError } from '../../exceptions/HttpError';

export class PermissionRepository {
  // 获取所有字典项
  async findAll(): Promise<Permission[]> {
    try {
      return await PermissionModel.find().sort({ type: 1, sort: 1, createdAt: -1 }).lean();
    } catch (error: any) {
      throw HttpError.internalServerError(`获取权限列表失败: ${error.message}`);
    }
  }



  // 根据ID获取菜单
  async findById(id: string): Promise<Permission | null> {
    try {
      const permission = await PermissionModel.findById(id).lean();
      if (!permission) {
        throw HttpError.notFound('权限不存在');
      }
      return permission;
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`获取权限信息失败: ${error.message}`);
    }
  }

  // 根据类型查找字典项
  async findByType(type: string): Promise<Permission[] | null> {
    try {
      return await PermissionModel.find({ type }).sort({ sort: 1 }).lean();
    } catch (error: any) {
      throw HttpError.internalServerError(`查找权限失败: ${error.message}`);
    }
  }

  // 创建用户
  async create(permissionData: Partial<Permission>): Promise<Permission> {
    try {
      const permission = new PermissionModel(permissionData);
      return await permission.save();
    } catch (error: any) {
      if (error.code === 11000) {
        throw HttpError.unprocessableEntity('角色已存在', error.errors);
      }
      if (error.name === 'ValidationError') {
        throw HttpError.unprocessableEntity('数据验证失败1', error.errors);
      }
      throw HttpError.internalServerError(`创建角色失败2: ${error.message}`);
    }
  }

  // 更新用户
  async update(id: string, permissionData: Partial<Permission>): Promise<Permission | null> {
    try {
      // 移除密码字段，防止通过更新接口修改密码
      const { ...updateData } = permissionData;

      const permission = await PermissionModel.findByIdAndUpdate(
        id,
        updateData,
        { new: true, runValidators: true }
      );
      if (!permission) {
        throw HttpError.notFound('权限不存在');
      }

      return permission;
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      if (error.code === 11000) {
        throw HttpError.conflict('权限已存在');
      }
      if (error.name === 'ValidationError') {
        throw HttpError.unprocessableEntity('数据验证失败', error.errors);
      }
      throw HttpError.internalServerError(`更新权限失败: ${error.message}`);
    }
  }

  // 删除用户
  async delete(id: string): Promise<boolean> {
    try {
      const result = await PermissionModel.findByIdAndDelete(id);
      if (!result) {
        throw HttpError.notFound('权限不存在');
      }
      return true;
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`删除权限失败: ${error.message}`);
    }
  }

  // 获取用户数量
  async count(): Promise<number> {
    try {
      return await PermissionModel.countDocuments();
    } catch (error: any) {
      throw HttpError.internalServerError(`统计权限数量失败: ${error.message}`);
    }
  }

  // 分页查询用户
  async findWithPagination(page: number = 1, limit: number = 10): Promise<{ list: Permission[], page: number, limit: number, total: number, pages: number }> {
    try {
      const skip = (page - 1) * limit;
      const [list, total] = await Promise.all([
        PermissionModel.find().sort({ createdAt: -1 }).skip(skip).limit(limit).lean(),
        PermissionModel.countDocuments()
      ]);

      return {
        list,
        total,
        page,
        limit,
        pages: Math.ceil(total / limit)
      };
    } catch (error: any) {
      throw HttpError.internalServerError(`分页查询权限失败: ${error.message}`);
    }
  }
}

export default new PermissionRepository();
